package com.yaoandw.givebook;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.Scanner;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.yaoandw.test.CommandTest;
import com.yaoandw.test.CommandTest.MyThread;


public class BookCrawlerCommand {
	private static Logger logger = Logger.getLogger(BookCrawlerCommand.class);
	private static String command_start = "start";
	private static String command_pause = "pause";
	private static String command_continue = "continue";
	private static String command_stop = "stop";
	private static String command_exit = "exit";
	private static boolean started = false;
	
	static Crawler crawler;
	static int i = 0;
	static{
		initLog4j();
	}
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		while(true){
			Scanner input=new Scanner(System.in);
			String command = input.next();
//			BufferedReader stdin =new BufferedReader(new InputStreamReader(System.in));
//			String command = stdin.readLine();
			if(command_exit.equals(command))
				System.exit(1);
			String rtn = execCommand(command);
			System.out.println(rtn);
		}

	}
	public static String execCommand(String command){
		String rtn = "";
		if(command == null || "".equals(command.trim()))
			rtn = "wrong param";
		else if(command_start.equals(command)){
			if(started){
				rtn = "the crawler has already started";
			}else{
				rtn = "start crawler";
				started = true;
				crawler =new BookCrawler();
				new Thread(crawler).start();
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
//				CommandTest.status = CommandTest.status_started;
//				new Thread(new CommandTest(). new MyThread()).start();
				
			}
		}else if(command_pause.equals(command)){
			rtn = ("pause crawler");
			crawler.pauseCarawler();
		}else if(command_continue.equals(command)){
			rtn = ("continue crawler");
			crawler.continueCarawler();
		}else if(command_stop.equals(command)){
			rtn = ("stop crawler");
			crawler.stopCarawler();
		}else
			rtn = ("wrong command");
		return rtn;
	}

	public static void initLog4j() {
		Properties props = new Properties();
		try {
			InputStream is = BookCrawler.class
					.getResourceAsStream("/log4j.properties");
			props.load(is);
			is.close();
			PropertyConfigurator.configure(props);// 装入log4j配置信息
		} catch (IOException e) {
			logger.error("", e);
			return;
		}

	}
}
